<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>

    <div id="root">
        
        <ul>
            <input type="text" placeholder="请输入关键词" v-model="keyWord">
            <button @click="sortType = 0">原排序</button>
            <button @click="sortType = 1">升序</button>
            <button @click="sortType = 2">降序</button>
            <li v-for="(p,index) in filPersons" :key="p.index">
                {{p.name}}--{{p.age}}--{{p.sex}}
            </li>
        </ul>
    </div>

    <script type="text/javascript">
        Vue.config.productionTip = false;//阻止vue在启动的时候生成生产提示

        // //数据监视实现过滤
        //#region
        // const vm = new Vue({
        //     el:"#root",
        //     data:{
        //         keyWord:'',
        //         persons:[
        //             {id:'001',name:'马冬梅',age:10,sex:'女'},
        //             {id:'002',name:'周冬雨',age:20,sex:'女'},
        //             {id:'003',name:'周杰伦',age:30,sex:'男'},
        //             {id:'004',name:'温兆伦',age:23,sex:'男'}
        //         ],
        //         filPersons:[]
        //     },
        //     watch:{
        //         keyWord:{
        //             immediate:true,
        //             handler(val){
        //                 this.filPersons=this.persons.filter((p)=>{
        //                     return p.name.indexOf(val)!==-1;
        //                 })
        //             }
        //         }
        //     }
        // })
        //#endregion
        
        //计算属性实现
        //#region
        const vm = new Vue({
            el:"#root",
            data:{
                sortType:0,//0是原排序，1是升序，2是降序
                keyWord:'',
                persons:[
                    {id:'001',name:'马冬梅',age:25,sex:'女'},
                    {id:'002',name:'周冬雨',age:20,sex:'女'},
                    {id:'003',name:'周杰伦',age:30,sex:'男'},
                    {id:'004',name:'温兆伦',age:23,sex:'男'}
                ]
            },
            computed:{
                //所依赖的属性变化时 调用计算属性
                filPersons(){
                    const arr = this.persons.filter((p)=>{
                        return p.name.indexOf(this.keyWord)!==-1;
                    })
                    //判断sortType的值，是否要排序
                    if(this.sortType){
                        arr.sort((a,b)=>{
                            return this.sortType === 1 ? a.age-b.age : b.age-a.age;
                        })
                    }
                    return arr;
                }
            }
        })
        //#endregion
    </script>
</body>
</html>